


interface OssUploaderItem{
    title:string;
    uploader:any;
    uploaderName:string;
}
interface OssFileItem{
    queue:any[];
    addByFile:(file)=>void;
    addByPath:(src:string)=>void;
    
}

class ossUploaderService {

    client: any;
    constructor(private http: ng.IHttpService, private route: routeService, private config: configService) {
        // console.log('11111111111');
        const configInfo = this.config.getConfig();
        this.client=new OSS.Wrapper(configInfo.ossConfig)
    }


    getOssFile() {
        const self = this;

        function OssFile(scope,uploader,config?){
            this.maxIndex=0;
            this.queue=[];
            this.scope=scope;
            this.uploader=uploader;
            this.uploaderList=config.uploaderList;
            this.multiple=config&&config.multiple||false;
            this.tag=config&&config.tag
        }
        OssFile.prototype.f5=function(){
            if (!this.scope.$$phase) {
                this.scope.$apply(() => { this.uploader });
            }
        }
        OssFile.prototype.upload=function(item){
            // console.log(item);
            const id=self.getUuid();
            const storeAs = 'upload/'+ id+ '.'+ item._file.name.split('.').pop()  // 保存的路径
            
            const this1=this;
            const f5=this.f5.bind(this1);
            self.client.multipartUpload(storeAs,item._file,{progress:(percent)=>{
                return function(done){
                    item.progress=percent;
                    f5();
                    done();
                }

            }}).then(result=>{
                
                if(result.res.status===200){
                    item.fileId=id;
                    item.progress=100;
                    item.isSuccess=true
                    
                    item.imgSrc=result.res.requestUrls[0].split('?')[0];
                    

                    this.onSuccess(item);
                    this.f5()
                }
                // let filePath = 



            }).catch(err => {
                // console.log(err);
            })

        };
        OssFile.prototype.uploadAll=function(){
            this.queue.forEach(element => {
                if(element._file&&!element.isSuccess){
                    this.upload(element)
                }
            });
        }
        OssFile.prototype.getNotUploadedItems=function(){
            return this.queue.filter(element=>{
                return element._file&&!element.isSuccess
            })
        }
        OssFile.prototype.addByFile=function(file){
            if(!this.multiple){
                this.queue=[]
            }
            const item={_file:file,index:this.maxIndex++,progress:0,fileName:file.name,fileSize:file.size }
            
            this.queue.push(item);
            this.onAfterAddingFile(item)
        }
        OssFile.prototype.addByPath=function(src,config?){
            if(src){
                if(!this.multiple){
                    this.queue=[]
                }
                let item = {imgSrc:src,index:this.maxIndex++,progress:100,isSuccess:true,fileId:config&&config.id,fileName:config&&config.name}
                this.queue.push(item);
                this.getFileSize(item,src)
                
            }

            
            
        }

        OssFile.prototype.addByAttach=function(attachment){
            let attachmentId = attachment.attachmentId || attachment[0];
            let attachmentName = attachment.attachmentName || attachment[1];
            let attachmentPath = attachment.attachmentPath || attachment[2];

            this.addByPath(attachmentPath,{id:attachmentId,name:attachmentName})
        }

        OssFile.prototype.onSuccess = function (res) {
            // console.log(res);
        }
        OssFile.prototype.onDelete= function(item){

            this.queue=this.queue.filter(it=>it.index!==item.index);

            for(let i=0;this.uploaderList.length>i;i++){
                let name = this.uploaderList[i].name || this.uploaderList[i].attachmentName || this.uploaderList[i][1];
                let path = this.uploaderList[i].path || this.uploaderList[i].attachmentPath || this.uploaderList[i][2];
                if (name == item.fileName && path == item.imgSrc) {
                    this.uploaderList.splice(i,1);
                    break;
                    // i=i-1;
                }
            }
            this.f5()
            
            this.afterDelete();
                
        }
        OssFile.prototype.onDownload = function (item) {

            let link: HTMLElement = document.createElement('a');
            link.setAttribute("href", item.imgSrc);
            link.setAttribute("download", `word.docx`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

        }

        OssFile.prototype.clearQueue=function(){
            this.queue=[];
            this.f5()

        }
        OssFile.prototype.afterDelete=function(){

        }
        OssFile.prototype.onAfterAddingFile=function(){

        }
        OssFile.prototype.getFileSize = function(item,src ){

            const fileType = src.split('.').pop();
            
            const ImgList=[ 'gif', 'png', 'jpg', 'jpeg','tiff'];

            if(ImgList.indexOf(fileType)>-1){
                 const url = src+'?x-oss-process=image/info'
                $.get(url,(data,status)=>{
                        // console.log('img info',data)
                        if(data.FileSize){
                            item.fileSize=data.FileSize.value;
                            this.f5()
                        }
                })
            }else{
                $.get(src,(data,status)=>{
                    // console.log(data.toString())
                    if(status==='success'){
                       
                        var blob = new Blob([data]);
                       
                        item.fileSize = blob.size;
                        this.f5()
                    }
                })
            }
           

           

          

           
            
            
            
        }


        
        


        return OssFile;

    }

    getUuid() {
        var len = 32; //32长度
        var radix = 16; //16进制
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0;  len>i; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0;  36>i; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }
    
        
}

angular.module("ossUploaderService", []).service("ossUploaderService", ['$http', 'routeService', 'configService', ossUploaderService]);